import 'dart:convert';

import 'package:whale/helper/global/keys.dart';
import 'package:whale/helper/utils/um/um_man.dart';

import '../../utils/util.dart';
import '../model/user/user_info.dart';
import 'state.dart';

class UserController {
  final state = UserState();

  static final UserController instance = UserController._interval();
  factory UserController() => instance;
  UserController._interval();

  String? loginAccount;
  String? loginPwd;

  Future<void> initData() async {
    String _token = SpUtil().getStr(key_store_user_token);
    if (_token.isEmpty) {
      return;
    }
    loginAccount = SpUtil().getStr(key_store_account);
    loginPwd = SpUtil().getStr(key_store_pwd);

    var userStr = await SpUtil().getJSON(key_store_user);
    if (userStr != null) {
      var userJson = jsonDecode(userStr);
      configUser(userJson);
      if (isLogin) {}
    }
  }

  Future<void> loginSuccess(Map<String, dynamic> userJson) async {
    configUser(userJson);
    // UmMan().onSignIn(state.user!.userId!);
    await save();
  }

  Future<void> loginOutSuccess() async {
    // isLogin = false;

    // EMClient.getInstance.chatManager.fetchHistoryMessages(conversationId)
    isLogin = false;
    state.user?.token = null;
    // UmMan().onSignOut();
    await SpUtil().remove(key_store_user_token);
    await SpUtil().remove(key_store_account);
    await SpUtil().remove(key_store_pwd);
  }

  void updateAvater(String avater) {
    if (state.user == null) {
      return;
    }
    // state.user?.updateAvater(avater);
    loginSuccess(state.user!.toJson());
  }

  void configUser(Map<String, dynamic> userJson) {
    isLogin = true;
    state.user = UserInfo.fromJson(userJson);
    state.userObs.value = state.user!;
    state.userObs.refresh();
  }

  final isLoginObs = false.obs;
  set isLogin(bool value) {
    isLoginObs.value = value;
    if (value == false) {
      SpUtil().remove(key_store_user_token);
    }
  }

  bool get isLogin {
    return !isNilStr(state.user?.token);
  }

  final isAtLoginObs = true.obs;
  set isAtLogin(bool value) => isAtLoginObs.value = value;
  bool get isAtLogin => isAtLoginObs.value;

  Future<bool> save() async {
    if (state.user != null) {
      var _json = state.user!.toJson();
      await SpUtil().setJSON(key_store_user, jsonEncode(_json));

      await SpUtil().setStr(key_store_user_token, state.user!.token!);
      return true;
    }
    return false;
  }

  Future<void> saveLogin({
    required String account,
    required String pwd,
  }) async {
    loginAccount = account;
    loginPwd = pwd;
    await SpUtil().setJSON(key_store_account, account);

    await SpUtil().setStr(key_store_pwd, pwd);
  }
}
